package com.hxzy.controller.admin;

import com.hxzy.common.consts.RedisConst;
import com.hxzy.common.controller.BaseController;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.vo.R;
import com.hxzy.dto.LoginDTO;
import com.hxzy.entity.Employee;
import com.hxzy.service.EmployeeService;
import com.hxzy.util.SSMThreadLocal;
import com.hxzy.util.TokenServiceUtil;
import com.hxzy.vo.AdminLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 后台员工登录API
 *
 * @author tonneyyy
 */
@RestController
@RequestMapping(value = "/api")
public class EmployeeLoginController extends BaseController{

    @Autowired
    private EmployeeService  employeeService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 令牌生成器
     */
    @Autowired
    private TokenServiceUtil  tokenServiceUtil;

    @PostMapping(value = "/login")
    public R login(@RequestBody  @Valid LoginDTO  loginDTO ){
        //验证验证码是否过期
        String redisKey= RedisConst.getRedisKey(RedisConst.CAPTCHA_KEY,loginDTO.getUuid());
        //查询键是不是存在
        Object redisValue=this.redisTemplate.opsForValue().get(redisKey);

        if(redisValue==null){
            return R.build(AckCode.SMS_CODE_OVERTIME);
        }
        //再判断值是否相等
        if(!redisValue.toString().equalsIgnoreCase(loginDTO.getCode())){
            return R.build(AckCode.SMS_CODE_WRONG);
        }
        //验证码验证成功，删除验证码
        this.redisTemplate.delete(redisKey);

        Employee employee= this.employeeService.login(loginDTO);
        //生成自定义对象，存储令牌
        String jwt=this.tokenServiceUtil.createJwtToken(employee);
        return R.okHasData(jwt);
    }

    @PostMapping(value = "/logout")
    public R logout(){
        AdminLoginVO adminLoginVO = SSMThreadLocal.adminLoginVOThreadLocal.get();
        String redisKey= RedisConst.getRedisKey(RedisConst.EMPLOYEE_KEY,adminLoginVO.getUuid());
        this.redisTemplate.delete(redisKey);
        return R.ok();
    }

    /**
     * 获取当前用户
     * @return
     */
    @GetMapping(value = "/user/info")
    public R getUserInfo(){
        AdminLoginVO adminLoginVO = SSMThreadLocal.adminLoginVOThreadLocal.get();
        return R.okHasData(adminLoginVO);
    }
}
